package com.zhaojk.audio.service;

import cn.hutool.extra.spring.SpringUtil;
import com.zhaojk.audio.domain.*;
import com.zhaojk.audio.domain.DTO.WordDefinition;
import com.zhaojk.audio.entity.Scene;
import com.zhaojk.audio.mapper.SceneMapper;
import com.zhaojk.audio.util.TimeTrace;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.*;
import java.util.function.Supplier;
import java.util.stream.Collectors;

/**
 * 训练计划
 * @author zhaojk
 */
@Service
@Slf4j
public class TrainingPlanServiceImpl {
    // 缓存页面类型与类的映射
    private static final Map<TrainingType, Supplier<TrainingPage>> PAGE_CREATORS = new EnumMap<>(TrainingType.class);

    // 服务实例缓存
    private VolcTextServiceImpl volcTextService;
    @Autowired
    private PromptTemplateServiceImpl promptTemplateService;

    @Autowired
    private SceneMapper sceneMapper;

    @PostConstruct
    public void init() {
        // 一次性初始化页面创建器
        for (TrainingType type : TrainingType.values()) {
            PAGE_CREATORS.put(type, () -> {
                try {
                    Class<?> clazz = Class.forName(type.getPageClassName());
                    return (TrainingPage) clazz.getDeclaredConstructor().newInstance();
                } catch (Exception e) {
                    log.error("Failed to create instance for {}", type.getPageClassName(), e);
                    return null;
                }
            });
        }

        // 获取服务实例（只获取一次）
        this.volcTextService = SpringUtil.getBean(VolcTextServiceImpl.class);
    }

    @TimeTrace("获取场景词汇")
    public TrainingPlan getTrainingPlan(String sceneId) {
            List<String> defIdList = sceneMapper.findDefsBySceneId(sceneId);
            // 直接获取特定场景的数据
            List<WordDefinition> filterData = sceneMapper.findWordsByDefIds(defIdList);
            TrainingPlan plan = generatePlan(filterData, sceneId);
            return plan;
    }

    private TrainingPlan generatePlan(List<WordDefinition> filterData, String sceneId) {
        if (filterData == null || filterData.isEmpty()) {
            return null;
        }

        TrainingPlan trainingPlan = new TrainingPlan();
        List<TrainingPage> pages = Collections.synchronizedList(new ArrayList<>());

        // 使用并行流处理
        filterData.parallelStream().forEach(item -> {
            Arrays.stream(TrainingType.values()).forEach(type -> {
                Supplier<TrainingPage> creator = PAGE_CREATORS.get(type);
                if (creator != null) {
                    TrainingPage page = creator.get();
                    if (page == null) {
                        return;
                    }

                    String targetWord = item.getLemma();

                    page.setType(type);
                    page.setCompleted(false);
                    page.setTargetWord(targetWord);

                    processPage(page, item, type);
                    pages.add(page);
                }
            });
        });
        TrainingPage.randomizePages(pages);
        trainingPlan.setSceneId(sceneId);
        trainingPlan.setPages(pages);
        return trainingPlan;
    }

    private void processPage(TrainingPage page, WordDefinition wordDefinition, TrainingType type) {
        if (page instanceof ImageChooseAudioPage) {
            ImageChooseAudioPage imageChooseAudioPage = (ImageChooseAudioPage) page;
            setupImageChooseAudioPage(imageChooseAudioPage, wordDefinition);
        } else if (page instanceof AudioChooseImagePage) {
            AudioChooseImagePage audioChooseImagePage = (AudioChooseImagePage) page;
            setupAudioChooseImagePage(audioChooseImagePage, wordDefinition);
        } else if (page instanceof AudioBasePage) {
            AudioBasePage audioPage = (AudioBasePage) page;
            setupAudioBasePage(audioPage, wordDefinition);
        }
    }

    private void setupImageChooseAudioPage(ImageChooseAudioPage page, WordDefinition wordDefinition) {
        // 设置Image数据
        ImageVo image = new ImageVo();
        WordVo word = new WordVo();
        //word.setText(targetWord);
        // 对生成图片的单词进行扩展
        String prompt = promptTemplateService.extendPrompt(wordDefinition.getLemma());
        word.setText(prompt);
        word.setTranslation(wordDefinition.getTranslation());
        List<WordVo> imageWords = new ArrayList<>();
        imageWords.add(word);
        image.setWords(imageWords);
        page.setImages(image);

        // 设置audio数据
        List<String> similarWords = volcTextService.getSimilarPronunciationToWord(wordDefinition);
        AudioVo audio = new AudioVo();
        List<WordVo> audioWords = new ArrayList<>();
        audioWords.add(new WordVo(wordDefinition.getLemma(), true));

        similarWords.forEach(similarWord -> audioWords.add(new WordVo(similarWord, false)));
        //随机排序答案
        Collections.shuffle(audioWords);
        audio.setWords(audioWords);
        page.setAudio(audio);
    }

    private void setupAudioChooseImagePage(AudioChooseImagePage page, WordDefinition wordDefinition) {
        // 设置audio数据
        AudioVo audio = new AudioVo();
        WordVo word = new WordVo();
        word.setText(wordDefinition.getLemma());
        word.setTranslation(wordDefinition.getTranslation());
        List<WordVo> audioWords = new ArrayList<>();
        audioWords.add(word);
        audio.setWords(audioWords);
        page.setAudio(audio);

        // 设置image数据
        List<String> similarWords = volcTextService.getSimilarPicToWord(wordDefinition);
        ImageVo image = new ImageVo();
        List<WordVo> imageWords = new ArrayList<>();
        imageWords.add(new WordVo(wordDefinition.getTranslation(), true));

        similarWords.forEach(similarWord -> {
            // 对生成图片的单词进行扩展
            String extendPrompt = promptTemplateService.extendPrompt(similarWord);
            imageWords.add(new WordVo(extendPrompt, false));

        });
        //随机排序答案
        Collections.shuffle(imageWords);
        image.setWords(imageWords);
        page.setImages(image);
    }

    private void setupAudioBasePage(AudioBasePage page, WordDefinition wordDefinition) {
        AudioVo audio = new AudioVo();
        WordVo word = new WordVo();
        word.setText(wordDefinition.getLemma());
        word.setTranslation(wordDefinition.getTranslation());
        word.setCorrect(true);
        List<WordVo> words = new ArrayList<>();
        words.add(word);
        audio.setWords(words);
        page.setAudio(audio);

        WordVo imgWord = new WordVo();
        // 对生成图片的单词进行扩展
        String extendPrompt = promptTemplateService.extendPrompt(wordDefinition.getLemma(), wordDefinition.getTranslation());
        imgWord.setText(extendPrompt);
        imgWord.setTranslation(wordDefinition.getTranslation());
        imgWord.setCorrect(true);
        List<WordVo> imgWords = new ArrayList<>();
        imgWords.add(imgWord);
        ImageVo imageVo = new ImageVo();
        imageVo.setWords(imgWords);
        page.setImages(imageVo);
    }
}
